//
//  AddNewAddressViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/1.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "AddNewAddressViewController.h"
#import "AddNewAddressCell.h"
#import "AddNewAddressBottomCell.h"
#import "AddNewAddressMiddleCell.h"
#import "GFAddressPicker.h"
#import "AddressManagerViewController.h"
@interface AddNewAddressViewController ()<GFAddressPickerDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *titlesArray;
@property (nonatomic, strong) GFAddressPicker *pickerView;
@property(nonatomic,copy)NSString *PCA_Id;
@end


@implementation AddNewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加地址";
    [self setRightBarbuttonItem];
    [self createUI];
}
-(void)setRightBarbuttonItem{
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(clickRightBarButtonItem:)
       forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(WIDTH - 30, 6, 40, 20);
    UIBarButtonItem *flexSpac = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpac.width = -10;
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItems = @[flexSpac,rightBtnItem];
}
-(void)clickRightBarButtonItem:(UIButton *)btn{
    [self addNewAddressAndResaveAddress];


}
-(void)createUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[AddNewAddressCell class] forCellReuseIdentifier:@"AddNewAddressCell"];
    [self.tableView registerClass:[AddNewAddressBottomCell class] forCellReuseIdentifier:@"AddNewAddressBottomCell"];
    [self.tableView registerClass:[AddNewAddressMiddleCell class] forCellReuseIdentifier:@"AddNewAddressMiddleCell"];
    UIView *view = [[UIView alloc] init];
    self.tableView.tableFooterView = view;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView reloadData];
}
#pragma mark -tablview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.titlesArray.count;
    }else if (section == 1){
        return 1;
    }else{
        return 1;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        AddNewAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddNewAddressCell"];
        cell.textfield.delegate = self;
        cell.labell.text = self.titlesArray[indexPath.row];
        return cell;
    }else if (indexPath.section == 1){
        AddNewAddressMiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddNewAddressMiddleCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }else{
        AddNewAddressBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddNewAddressBottomCell"];
        cell.textview.delegate = self;
        return cell;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return 50.f;
    }else{
        return 100.f;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
    }else if (indexPath.section == 1){
        
        self.pickerView = [[GFAddressPicker alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        [self.pickerView updateAddressAtProvince:@"上海市" city:@"上海市" town:@"宝山区"];
        self.pickerView.delegate = self;
        self.pickerView.font = [UIFont boldSystemFontOfSize:18];
        [self.view addSubview:self.pickerView];
    }else{
        
    }
}
- (void)GFAddressPickerCancleAction
{
    [self.pickerView removeFromSuperview];
}

- (void)GFAddressPickerWithProvince:(NSString *)province
                               city:(NSString *)city area:(NSString *)area
{
    [self.pickerView removeFromSuperview];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:1];
    AddNewAddressMiddleCell * cell = [self.tableView cellForRowAtIndexPath:indexpath];
    cell.labl.text = [NSString stringWithFormat:@"%@  %@  %@",province,city,area];
    [self accodringAddressInformationBackIdWithProvince:province AndCity:city AndArea:area];
    
    NSLog(@"%@  %@  %@",province,city,area);
}

/**
 根据地理信息返回ID
 */
-(void)accodringAddressInformationBackIdWithProvince:(NSString *)province AndCity:(NSString *)city AndArea:(NSString *)area{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/pcaApp/list";
    NSDictionary *param = @{@"groupBy":@"2",@"province":province,@"city":city,@"area":area};
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *detailDic = jsonDic[@"list"][0];
        self.PCA_Id = detailDic[@"id"];
        NSLog(@"这是你要的ID%@",self.PCA_Id);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:2];
    AddNewAddressBottomCell *cell = [self.tableView cellForRowAtIndexPath:indexpath];
    cell.placeholderLabel.alpha = 0;
//    if (!textView.text.length) {
//        cell.placeholderLabel.alpha = 1;
//    } else {
//        cell.placeholderLabel.alpha = 0;
//    }
    return YES;
}
//textview的代理方法
- (void)textViewDidChange:(UITextView *)textView {
//    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:2];
//    AddNewAddressBottomCell *cell = [self.tableView cellForRowAtIndexPath:indexpath];
//    if (!textView.text.length) {
//        cell.placeholderLabel.alpha = 1;
//    } else {
//       cell.placeholderLabel.alpha = 0;
//    }
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if([text isEqualToString:@"\n"]){
        
        [textView resignFirstResponder];
        
        return NO;
        
    }
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(NSArray *)titlesArray{
    if (_titlesArray == nil) {
        _titlesArray = @[@"收货人",@"联系电话"];
    }
    return _titlesArray;
}

-(void)addNewAddressAndResaveAddress{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/addressApp/saveOrUpdateAddress";
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSIndexPath *indexpath1 = [NSIndexPath indexPathForRow:0 inSection:0];
    AddNewAddressCell *cell1 = [self.tableView cellForRowAtIndexPath:indexpath1];
    NSIndexPath *indexpath2 = [NSIndexPath indexPathForRow:1 inSection:0];
    AddNewAddressCell *cell2 = [self.tableView cellForRowAtIndexPath:indexpath2];
    NSIndexPath *indexpath3 = [NSIndexPath indexPathForRow:0 inSection:2];
    AddNewAddressBottomCell *cell3 = [self.tableView cellForRowAtIndexPath:indexpath3];
    if (cell3.textview.text && cell1.textfield.text && cell2.textfield.text && self.PCA_Id) {
        NSDictionary *param = @{@"sessionId":sessionId,@"name":@"1",@"pca.Id":self.PCA_Id,@"phoneNumber":cell2.textfield.text,@"collectName":cell1.textfield.text,@"address":cell3.textview.text};
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"成功的%@",jsonDic[@"msg"]);
                [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"失败%@",error);
        }];

    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"信息填写不完整" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
}
@end
